package org.tim.es.webapi;

import com.google.common.base.Preconditions;
import io.swagger.annotations.ApiOperation;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.tim.common.util.Sessions;
import org.tim.es.message.UserPrivateMessageResource;
import org.tim.es.session.UserPrivareSessionResource;
import org.tim.es.session.UserPrivateSession;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/private_session")
public class PrivateSessionController {
    @Autowired
    private UserPrivareSessionResource userPrivareSessionResource;

    @Autowired
    private UserPrivateMessageResource userPrivateMessageResource;

    @GetMapping
    @ApiOperation("获取当前用户某个时间内的会话记录")
    public Page<UserPrivateSession> findSessionByDate(@RequestParam String userId,
                                                      @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime localDateTime) {
        return userPrivareSessionResource.findBy(userId, localDateTime);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除会话")
    public void deleteSession(@PathVariable String id) {
        userPrivareSessionResource.deleteById(id);

        /* 级联删除当前会话的消息 */
        userPrivateMessageResource.deleteAllBySessionId(id);
    }

    @PostMapping
    @ApiOperation("创建会话")
    public UserPrivateSession saveSession(@RequestBody UserPrivateSession userPrivateSession) {
        userPrivateSession.setLastSessionAt(LocalDateTime.now());
        userPrivateSession.setCreatedAt(LocalDateTime.now());
        userPrivateSession.setDelete(Boolean.FALSE);
        return userPrivareSessionResource.save(userPrivateSession);
    }

    @PostMapping("/trysession")
    @ApiOperation("尝试建立会话，如果会话不存在，创建会话")
    public UserPrivateSession trySession(@RequestBody UserPrivateSession userPrivateSession) {
        Preconditions.checkNotNull(userPrivateSession);
        Preconditions.checkNotNull(userPrivateSession.getFromUserId());
        Preconditions.checkNotNull(userPrivateSession.getToUserId());

        var sessionId = Sessions.getSessionId(userPrivateSession.getFromUserId(), userPrivateSession.getToUserId());
        var sessionPresent = userPrivareSessionResource.findById(sessionId);
        if (sessionPresent.isPresent()) {
            return sessionPresent.get();
        } else {
            /* 创建会话 */
            userPrivateSession.setId(sessionId);
            userPrivateSession.setLastSessionAt(LocalDateTime.now());
            userPrivateSession.setCreatedAt(LocalDateTime.now());
            userPrivateSession.setDelete(Boolean.FALSE);
            return userPrivareSessionResource.save(userPrivateSession);
        }
    }
}
